package com.zhang.study.chapter04;

import java.util.Arrays;

import static com.zhang.util.RandomArrayUtil.generateRandomArray;

/**
 * 归并排序 迭代实现
 */
public class Code02_MergeSortByIteration {

    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length == 0) {
            return;
        }
        // 定义步长
        int mergeSize = 1;
        while (mergeSize < arr.length) {
            int left = 0;
            while (left < arr.length) {
                int mid = left + mergeSize - 1;
                // 判断是否需要合并
                if (mid >= arr.length) {
                    break;
                }
                int right = Math.min(mid + mergeSize, arr.length - 1);
                merge(arr, left, mid, right);
                left = right + 1;
            }
            if (mergeSize > arr.length >> 1) {
                break;
            }
            mergeSize <<= 1;
        }
    }

    private static void merge(int[] arr, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = left;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= right) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= right) {
            temp[k++] = arr[j++];
        }
        i = 0;
        for (int l = left; l <= right; l++) {
            arr[l] = temp[i++];
        }
    }

    public static void main(String[] args) {
        int maxSize = 100;
        int maxValue = 100;
        int testTime = 50000;
        System.out.println("test begin!");
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            int[] arr2 = arr1.clone();
            mergeSort(arr1);
            Arrays.sort(arr2);
            if (!Arrays.equals(arr1, arr2)) {
                System.out.println("Oops!");
                return;
            }
        }
        System.out.println("Nice!");
        System.out.println("test end!");
    }

}
